package com.zhentao.common.config.log;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;

/**
 * @Date 2024/6/21 14:28
 * @Author xdm
 **/
@Component  //保证spring启动的时候扫描--bean
@Aspect  //申明切面
@Slf4j
public class LogConfig {

    //切入点表达式  -controller每一个方法里面
    @Pointcut("execution(* com.zhentao.controller.*.*(..)  )")
    public void pointcut() {
    }

    //环绕通知
    @SneakyThrows
    @Around("pointcut()")
    public Object aspectLog(ProceedingJoinPoint joinPoint) {
        //通过request可以获取到请求的url ,ip地址等信息
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //访问路径
        String uri = request.getRequestURI();
        //ip地址
        String ip = request.getRemoteAddr();
        //请求方式
        String method = request.getMethod();

        //类名
        String cls = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        //参数
        Object[] args = joinPoint.getArgs();
        //执行结果
        Object object = joinPoint.proceed();  //放行的方法

        //保持日志
        log.info("ip:{}\t url:{}\t method:{}\t cls:{}\t methodName:{} \t,参数：{}" +
                "\t result:{} " ,ip,uri,method,cls,methodName,args,object);

        //某些记录需要保存数据库
        return object;
    }


}